﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using UnionnetClient.Model;
using Microsoft.Win32;

namespace UnionnetClient
{
	public partial class SettingsForm : Form
	{
		private ErrorProvider ep = new ErrorProvider();

		public SettingsForm()
		{
			InitializeComponent();
			LoadSetting();

			if (AppEnvironment.CurrentState is UnconfigState)
			{
				((UnconfigState)AppEnvironment.CurrentState).GetLoginSourceCompleted += delegate(object sender, EventArgs e)
				{
					LoginSourceRight();
				};
			}
		}

		#region 事件处理函数

		private void btnOk_Click(object sender, EventArgs e)
		{
			if (ValidateSetting())
			{
				StoreSetting();

				this.DialogResult = DialogResult.OK;
			}
			else
			{
				MessageBox.Show("设置信息有误,请重新设置!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			if (DialogResult.OK == openFileDialog1.ShowDialog())
			{
				StreamReader sr = new StreamReader(openFileDialog1.FileName);
				string content = sr.ReadToEnd();
				sr.Close();

				if (!ValidateSoureFile(content))
				{
					MessageBox.Show("文件格式不正确,无法解析.","错误 - 聚友登陆客户端", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else
				{
					LoginSourceRight();
					AppEnvironment.Settings[SettingsProperty.LoginSource] = content;
				}
			}
		}

		private void EmptyValidating(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (sender is TextBox)
			{
				if (((TextBox)sender).Text.Length == 0)
				{
					ep.SetError((TextBox)sender, "不能为空");
				}
				else
				{
					ep.SetError((TextBox)sender, "");
				}
			}
		}

		#endregion


		#region 辅助函数

		private void LoadSetting()
		{
			txtUsername.Text = AppEnvironment.Settings.Username;
			txtPassword.Text = AppEnvironment.Settings.Password;
			numLoginTimeout.Value = AppEnvironment.Settings.LoginTimeout / 1000;
			numLoginAttamptInterval.Value = AppEnvironment.Settings.LoginAttemptInterval / 1000;

			chkAutoLogin.Checked = (bool)AppEnvironment.Settings[SettingsProperty.AutoLogin];
			chkVPN.Checked = AppEnvironment.Settings.IsVPN;
			chkAutoRun.Checked = IsAutorun();

			if (AppEnvironment.Settings.IsLoginSourceCorrect)
			{
				LoginSourceRight();
			}
			else
			{
				lbSourceState.ForeColor = Color.Red;
				lbSourceState.Text = "异常";
			}
		}

		private void StoreSetting()
		{
			AppEnvironment.Settings.SetAccount(txtUsername.Text, txtPassword.Text);

			AppEnvironment.Settings.LoginAttemptInterval = (int)numLoginAttamptInterval.Value * 1000;
			AppEnvironment.Settings.LoginTimeout = (int)numLoginTimeout.Value * 1000;

			AppEnvironment.Settings[SettingsProperty.AutoLogin] = chkAutoLogin.Checked;
			AppEnvironment.Settings.IsVPN = chkVPN.Checked;
			SetAutorun(chkAutoRun.Checked);

			AppEnvironment.Settings.Save();
		}

		private bool ValidateSetting()
		{
			return !(txtUsername.Text.Length == 0 || txtPassword.Text.Length == 0);
		}

		private bool ValidateSoureFile(string content)
		{
			return content.Contains("form") && content.Contains("vpn") && content.Contains("uid");
		}

		/// <summary>
		/// 设置或取消开机自动启动
		/// </summary>
		/// <param name="autorun">是否开机自动启动</param>
		private void SetAutorun(bool autorun)
		{
			RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
			string name = "聚友登陆客户端";

			if (autorun)
			{
				string exeDir = System.Reflection.Assembly.GetExecutingAssembly().Location;
				key.SetValue(name, exeDir, RegistryValueKind.String);
			}
			else
			{
				key.DeleteValue(name, false);
			}
			key.Close();
		}

		private bool IsAutorun()
		{
			RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
			string name = "聚友登陆客户端";
			bool b = null != key.GetValue(name, null);
			key.Close();
			return b;
		}

		private void LoginSourceRight()
		{
			lbSourceState.ForeColor = Color.Green;
			lbSourceState.Text = "正常";
		}

		#endregion
	}
}
